
package com.zhu.salesmanagement;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.Log;
import com.zhu.salesmanagement.common.MyLocation;
import com.zhu.salesmanagement.common.MyLocation.LocationResult;
import com.zhu.salesmanagement.models.AddedStoreItemInfo;
import com.zhu.salesmanagement.models.RemindItemInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.DialogUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 新增门店
 */

public class AddStoreActivity extends Activity implements View.OnClickListener {

	public static final String DATAID = "dbid";
	private final static String SPLIT_TYPE = "&";
    private MyLocation mMyLocation = null; //GPS定位
    private Location mCurLocation = null;
    private Uri mImageCaptureUri = null;
    private final static int INVALID_VALUE = -100;
    private static final int PICK_FROM_CAMERA = 0; //照相
    private static final int CROP_FROM_CAMERA = 1; //裁剪照片
    private static final int UPDATECONTENT = 2;
    private Bitmap mPhoto = null;
    private boolean mPhotoChanged = false;
    private TextView mInfoButton = null;
    private int mCurType = -1;
    private String[] mTypeArray = null;
    private boolean isNeedShowSave = false;
    private EditText mContact = null;
    private EditText mMobile = null;
    private EditText mAddress = null;
    private EditText mName = null;
    private long mDBId = INVALID_VALUE; //记录数据库主键ID
    private boolean isAddNewStore = true; //是否是新增门店
    private AddedStoreItemInfo mAddedStoreItemInfo = null;
    private ImageView mPhotoPreview = null;
    private String[] mTypeValue = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Parcelable parcelable = getIntent().getParcelableExtra("info");
        mAddedStoreItemInfo = (AddedStoreItemInfo) parcelable;
        //mTypeValue = getResources().getStringArray(R.array.store_type_value);
        if(mAddedStoreItemInfo != null){
        	mDBId = mAddedStoreItemInfo.id;
        }

        if(mDBId != INVALID_VALUE){
        	isAddNewStore =false;
        }else{
        	isAddNewStore = true;
        }

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_addstore);

        setupView();
        initData();
    }

    /**
     * 初始化界面
     */
    private void setupView() {
        findViewById(R.id.addstore_back).setOnClickListener(this);
        findViewById(R.id.addstore_bottom_back).setOnClickListener(this);
        //findViewById(R.id.addstore_commmit).setOnClickListener(this);
        if(mDBId != INVALID_VALUE){
            findViewById(R.id.addstore_takephoto).setVisibility(View.GONE);
        }else{
            findViewById(R.id.addstore_takephoto).setOnClickListener(this);
        }

        mInfoButton = (TextView) findViewById(R.id.addstore_storeinfo);
        mInfoButton.setOnClickListener(this);
        mContact = (EditText)findViewById(R.id.addstore_contact);
        mMobile = (EditText)findViewById(R.id.addstore_mobile);
        mAddress = (EditText)findViewById(R.id.addstore_address);
        mName = (EditText)findViewById(R.id.addstore_name);
        mPhotoPreview = (ImageView)findViewById(R.id.addstore_photopreview);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        if (mMyLocation == null && isAddNewStore) {
            mMyLocation = new MyLocation(AddStoreActivity.this, false, false);
            mMyLocation.getLocation(locationResult, false); //开始定位
        }

        if(mTypeArray == null){
            mTypeArray = getResources().getStringArray(R.array.store_type);
        }
        if(mAddedStoreItemInfo != null){
            mContact.setText(mAddedStoreItemInfo.mContact);
            mMobile.setText(mAddedStoreItemInfo.mMobile);
            mAddress.setText(mAddedStoreItemInfo.mAddress);
            mName.setText(mAddedStoreItemInfo.mName);
            ((TextView) findViewById(R.id.addstore_title)).setText(mAddedStoreItemInfo.mName);
            parseType();
        }
        if(mPhoto == null){
            setBitmapFromCursor();
        }
        updateInfoText();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        if (mMyLocation != null) {
            mMyLocation.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Actions.setAutoTime(this);
    }

    /**
     * button事件处理
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.addstore_back://返回
                    finish();
                    break;
                case R.id.addstore_bottom_back: //保存
                //case R.id.addstore_commmit:
                    saveData();
                    break;
                case R.id.addstore_takephoto: //照相
                    takePhoto();
                    break;
                case R.id.addstore_storeinfo: //门店属性
                    gotoStoreInfoActivity();
                    break;
            }
        }
    }

    /**
     * 跳转门店属性界面
     */
    private void gotoStoreInfoActivity(){
        Intent intent = new Intent(this, StoreInfoActivity.class);
        if(mAddedStoreItemInfo != null){
            Bundle bundle = new Bundle();
            bundle.putParcelable("info", mAddedStoreItemInfo);
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, UPDATECONTENT);
    }

    /**
     * 定位结果返回
     */
    public LocationResult locationResult = new LocationResult() {

        public void gotLocation(final Location location) {
            // Got the location!
            if (location != null) {
                mCurLocation = location;
                
            }
                
            if(isNeedShowSave){
                if(location == null){
                    Actions.toastShort(AddStoreActivity.this, getString(R.string.getlocationfailsave));
                }else{
                    Actions.toastShort(AddStoreActivity.this, getString(R.string.getlocationsuccesssave));
                }
                isNeedShowSave = false;
            }
        }
    };

    /**
     * 照相判断
     */
    private void takePhoto() {
    	if(!isAddNewStore){
    		Actions.toastShort(this, this.getString(R.string.cannotchangephoto));
    		return;
    	}
        if (mPhoto != null) {
            popTakePhotoDialog();
        } else {
            doTakePhotoAction();
        }
    }

    /**
     * 处理照相
     */
    private void doTakePhotoAction() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                            "tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        try {
            intent.putExtra("return-data", true);
            startActivityForResult(intent, PICK_FROM_CAMERA);
        } catch (ActivityNotFoundException e) {
            // Do nothing for now
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case CROP_FROM_CAMERA: { //裁剪结果
                final Bundle extras = data.getExtras();
                if (extras != null) {
                    if (mPhoto != null && !mPhoto.isRecycled()) {
                        mPhoto.recycle();
                        mPhoto = null;
                    }
                    Bitmap photo = extras.getParcelable("data");
                    mPhoto = photo;
                    mPhotoChanged = true;
                    // Log.e("zhu", photo.getWidth() + " " + photo.getHeight());
                    mPhotoPreview.setImageBitmap(photo);
                    mPhotoPreview.setVisibility(View.VISIBLE);
                    //saveMyBitmap("zhu", photo);
                }
                // Delete the temporary file
                File f = new File(mImageCaptureUri.getPath());
                if (f.exists()) {
                    f.delete();
                }
                break;
            }
            case PICK_FROM_CAMERA: { //照相结果
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(mImageCaptureUri, "image/*");
                intent.putExtra("outputX", 320);
                intent.putExtra("outputY", 240);
                // intent.putExtra("aspectX", 1);
                // intent.putExtra("aspectY", 1);
                // intent.putExtra("scale", "true");
                // intent.putExtra("crop", "true");
                // intent.putExtra("noFaceDetection", true);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, CROP_FROM_CAMERA);
//                try {
//                    mPhoto = scaleImg(android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageCaptureUri), 300, 300);
//                } catch (Exception e){
//
//                }
//                if(mPhoto != null){
//                    mPhotoChanged = true;
//                    mPhotoPreview.setImageBitmap(mPhoto);
//                    mPhotoPreview.setVisibility(View.VISIBLE);
//                    //saveMyBitmap("zhu", mPhoto);
//                }
                break;
            }
            case UPDATECONTENT: //内容更新
                Parcelable parcelable = data.getParcelableExtra("resultinfo");
                AddedStoreItemInfo info = (AddedStoreItemInfo) parcelable;
                if(mAddedStoreItemInfo == null){
                    mAddedStoreItemInfo = new AddedStoreItemInfo();
                }
                mAddedStoreItemInfo.copyFrom(info);
                updateInfoText();
                break;
        }
    }

    /**
     * 图片缩放
     * @param bm 原图片
     * @param newWidth 宽
     * @param newHeight 高
     */
    protected Bitmap scaleImg(Bitmap bm, int newWidth, int newHeight) {
     // 图片源
     // Bitmap bm = BitmapFactory.decodeStream(getResources()
     // .openRawResource(id));
     // 获得图片的宽高
     int width = bm.getWidth();
     int height = bm.getHeight();
     // 设置想要的大小
     int newWidth1 = newWidth;
     int newHeight1 = newHeight;
     // 计算缩放比例
     float scaleWidth = ((float) newWidth1) / width;
     float scaleHeight = ((float) newHeight1) / height;
     // 取得想要缩放的matrix参数
     Matrix matrix = new Matrix();
     matrix.postScale(scaleWidth, scaleHeight);
     // 得到新的图片
     Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
     true);
     return newbm;

     }

    /**
     * 保存图片至SD卡
     * @param mBitmap 原图片
     * @param bitName 保存图片名字
     */
    public void saveMyBitmap(String bitName, Bitmap mBitmap) {
        File f = new File("/sdcard/" + bitName + ".jpg");
        try {
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();
        } catch (IOException e) {

        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 照相覆盖提示
     */
    private void popTakePhotoDialog() {
        Actions.alertShowDetails(this, getString(R.string.shifoufugai),
                getString(R.string.shifoufugai_content),
                R.string.queding, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        doTakePhotoAction();
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

    private void popSelectTypeDialog() {
//        new AlertDialog.Builder(this)
//                .setTitle(R.string.select_type)
//                .setAdapter(new ArrayAdapter(AddStoreActivity.this, R.layout.choice_item, mTypeArray),
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog,
//                                    int which) {
//                                mCurType = which;
//                                mTypeButton.setText(mTypeArray[which]);
//                            }
//                        }).show();
    }

    /**
     * 保存新增门店数据
     */
    private void saveData(){
    	if(!isAddNewStore || isGetLocationSuccess()){
    		String name = mName.getText().toString().toString();
    		String address = mAddress.getText().toString().toString();
    		String mobile = mMobile.getText().toString().toString();
    		String contact = mContact.getText().toString().toString();

    		if(name.length() < 1 || address.length() < 1 || mobile.length() < 1 || contact.length() < 1 || (isAddNewStore && mPhoto == null)){
    			Actions.toastShort(this, getString(R.string.addstore_savefail));
    			return;
    		}

    		ContentValues values = new ContentValues();
            ContentResolver cr = getContentResolver();
            values.put(SalesSettings.MyAddStoresColumns.NAME, name);
            values.put(SalesSettings.MyAddStoresColumns.ADDRESS, address);
            values.put(SalesSettings.MyAddStoresColumns.MOBILE, mobile);
            values.put(SalesSettings.MyAddStoresColumns.CONTACT, contact);
            values.put(SalesSettings.MyAddStoresColumns.TYPE, StoreInfoActivity.TYPE_NEWSTORE);
            //values.put(SalesSettings.MyAddStoresColumns.TYPE, getStoreType());
            if(mAddedStoreItemInfo != null){
                values.put(SalesSettings.MyAddStoresColumns.SP1, mAddedStoreItemInfo.mSp1);
                values.put(SalesSettings.MyAddStoresColumns.SP2, mAddedStoreItemInfo.mSp2);
                values.put(SalesSettings.MyAddStoresColumns.SP3, mAddedStoreItemInfo.mSp3);
                values.put(SalesSettings.MyAddStoresColumns.SP4, mAddedStoreItemInfo.mSp4);
                values.put(SalesSettings.MyAddStoresColumns.SP5, mAddedStoreItemInfo.mSp5);
                values.put(SalesSettings.MyAddStoresColumns.SP6, mAddedStoreItemInfo.mSp6);
                values.put(SalesSettings.MyAddStoresColumns.SP7, mAddedStoreItemInfo.mSp7);
                values.put(SalesSettings.MyAddStoresColumns.SP8, mAddedStoreItemInfo.mSp8);
                values.put(SalesSettings.MyAddStoresColumns.SP9, mAddedStoreItemInfo.mSp9);
                values.put(SalesSettings.MyAddStoresColumns.SP10, mAddedStoreItemInfo.mSp10);
                values.put(SalesSettings.MyAddStoresColumns.SP11, mAddedStoreItemInfo.mSp11);
                values.put(SalesSettings.MyAddStoresColumns.SP12, mAddedStoreItemInfo.mSp12);
                values.put(SalesSettings.MyAddStoresColumns.SP13, mAddedStoreItemInfo.mSp13);
                values.put(SalesSettings.MyAddStoresColumns.SP14, mAddedStoreItemInfo.mSp14);
            }

            if(isAddNewStore){
                if(mCurLocation == null){
                    values.put(SalesSettings.MyAddStoresColumns.LAT, 0);
                    values.put(SalesSettings.MyAddStoresColumns.LNG, 0);
                }else{
                    values.put(SalesSettings.MyAddStoresColumns.LAT, mCurLocation.getLatitude());
                    values.put(SalesSettings.MyAddStoresColumns.LNG, mCurLocation.getLongitude());
                }
                values.put(SalesSettings.MyAddStoresColumns.PHOTO, flattenBitmap(mPhoto));
            }

            if (mDBId == INVALID_VALUE) {
                cr.insert(SalesSettings.MyAddStoresColumns.CONTENT_URI, values);
            } else {
                values.put(SalesSettings.MyAddStoresColumns._ID, mDBId);
                cr.update(SalesSettings.MyAddStoresColumns.getContentUri(mDBId, false), values, null,
                        null);
            }
            Actions.toastShort(this, this.getString(R.string.save_success));
            setResult(RESULT_OK);
            finish();
    	}
    }

//    private String getStoreType(){
//    	String type = mTypeValue[mCurType]; /*+ SPLIT_TYPE + mTypeArray[mCurType]*/;
//    	return type;
//    }

    private void parseType(){
//    	for(int i = 0; i < mTypeValue.length; i++){
//    		if(mAddedStoreItemInfo.mType.equals(mTypeValue[i])){
//    			mCurType = i;
//    		}
//    	}
//    	//mCurType = Integer.parseInt(mAddedStoreItemInfo.mType);
//    	mTypeButton.setText(mTypeArray[mCurType]);
    }

    /**
     * 是否成功获取位置数据
     */
    private boolean isGetLocationSuccess(){
    	if(mMyLocation != null && !mMyLocation.isGetLocationing()){
    		return true;
    	}
    	Actions.toastShort(this, getString(R.string.getlocationnotsave));
    	isNeedShowSave = true;
    	return false;
    }

    /**
     * 转换图片为二进制数据
     * @param bitmap 原图
     */
    private byte[] flattenBitmap(Bitmap bitmap) {
        int size = bitmap.getWidth() * bitmap.getHeight() * 4;
        ByteArrayOutputStream out = new ByteArrayOutputStream(size);
        try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
            Log.e("Could not write icon");
            return null;
        }
    }

    /**
     * 读取数据库中保存的图片
     */
    private void setBitmapFromCursor(){
        if(mDBId != INVALID_VALUE){
            Cursor cursor = this.getContentResolver().query(SalesSettings.MyAddStoresColumns.getContentUri(mDBId, false), null, null, null, null);
            if(cursor != null && cursor.moveToFirst()){
                byte[] data = cursor.getBlob(cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.PHOTO));
                mPhoto = BitmapFactory.decodeByteArray(data, 0, data.length);
                if(mPhoto != null){
                    mPhotoPreview.setImageBitmap(mPhoto);
                    mPhotoPreview.setVisibility(View.VISIBLE);
                }
            }
            if(cursor != null){
            	cursor.close();
            	cursor = null;
            }
        }
    }

    /**
     * 更新属性数据
     */
    private void updateInfoText(){
        if(mAddedStoreItemInfo != null && mAddedStoreItemInfo.mSp1 != null && mAddedStoreItemInfo.mSp1.trim().length() > 1){
            mInfoButton.setText(mAddedStoreItemInfo.mSp1);
        }else{
            mInfoButton.setText(null);
        }
    }
}
